package com.chunxuan.langquan.wxapi;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.chunxuan.langquan.base.Config;
import com.chunxuan.langquan.base.MyApp;
import com.chunxuan.langquan.support.util.Logg;
import com.google.gson.Gson;
import com.ruitu.arad.Arad;
import com.ruitu.arad.util.ToastUtils;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
    private IWXAPI api;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        api = WXAPIFactory.createWXAPI(this, Config.WX_APP_ID, false);

        try {
            Intent intent = getIntent();
            api.handleIntent(intent, this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        setIntent(intent);
        api.handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq baseReq) {
        Logg.e("onReq");
    }

    @Override
    public void onResp(BaseResp baseResp) {
        // 小程序回调
        if (baseResp.getType() == ConstantsAPI.COMMAND_LAUNCH_WX_MINIPROGRAM) {
            WXLaunchMiniProgram.Resp launchMiniProResp = (WXLaunchMiniProgram.Resp) baseResp;
            String extraData = launchMiniProResp.extMsg; //对应小程序组件 <button open-type="launchApp"> 中的 app-parameter 属性
            Logg.e("==extraData = " + extraData);
        }
        //登录回调
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                try {
                    String code = ((SendAuth.Resp) baseResp).code;
                    Logg.e("==wxLoginCode==" + code);
                    //获取accesstoken
                    getAccessToken(code);
                } catch (Exception e) {
                    e.printStackTrace();
                    finish();
                }
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED://用户拒绝授权
                ToastUtils.showShort("您拒绝了微信登录");
                finish();
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL://用户取消
                ToastUtils.showShort("您取消了微信登录");
                finish();
                break;
            default:
                finish();
                break;
        }
    }

    private void getAccessToken(String code) {
        createProgressDialog();
        //获取授权
        StringBuffer loginUrl = new StringBuffer();
        loginUrl.append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=")
                .append(Config.WX_APP_ID)
                .append("&secret=")
                .append(Config.WX_APP_SECRET)
                .append("&code=")
                .append(code)
                .append("&grant_type=authorization_code");
        Logg.e("==getAccessTokenUrl== " + loginUrl.toString());
//        Arad.preferences.putString("AccessTokenUrl", loginUrl.toString()).flush();
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(loginUrl.toString())
                .get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Logg.e("==getAccessToken," + "onFailure: ");
                mProgressDialog.dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseInfo = response.body().string();
                Logg.e("==getAccessToken," + "onResponse: " + responseInfo);
//                Arad.preferences.putString("AccessToken", responseInfo).flush();
                Arad.preferences.putString("wxUserInfo", responseInfo).flush();
                String access = null;
                String openId = null;
                try {
                    JSONObject jsonObject = new JSONObject(responseInfo);
                    access = jsonObject.getString("access_token");
                    openId = jsonObject.getString("openid");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                getUserInfo(access, openId);
            }
        });
    }

    private void getUserInfo(String access, String openid) {
        String getUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access + "&openid=" + openid;
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(getUserInfoUrl)
                .get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Logg.e("==getUserInfo," + "onFailure: ");
                mProgressDialog.dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseInfo = response.body().string();
                Logg.e("==getUserInfo," + "onResponse: " + responseInfo);
//                SharedPreferences.Editor editor = getSharedPreferences("userInfo", MODE_PRIVATE).edit();
//                editor.putString("responseInfo", responseInfo);
//                editor.commit();
                Arad.preferences.putString("wxUserInfo1", responseInfo).flush();
                finish();
                mProgressDialog.dismiss();
            }
        });
    }

    ProgressDialog mProgressDialog;

    private void createProgressDialog() {
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);//转盘
        mProgressDialog.setCancelable(false);
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setTitle("温馨提示");
        mProgressDialog.setMessage("微信登录中..");
        mProgressDialog.show();
    }
}
